package com.http;


import com.google.gson.Gson;
import com.model.TTSResponse;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Map;

public class TTSHttpClient {
    private final String baseUrl;
    private final Gson gson = new Gson();

    public TTSHttpClient(String baseUrl) {
        this.baseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl;
    }

    public String textToSpeech(Map<String, Object> payload) throws IOException {
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(baseUrl + "/tts");
            httpPost.setEntity(new StringEntity(gson.toJson(payload), ContentType.APPLICATION_JSON));

            try (CloseableHttpResponse response = client.execute(httpPost)) {
                HttpEntity entity = response.getEntity();
                TTSResponse ttsResponse = gson.fromJson(EntityUtils.toString(entity), TTSResponse.class);

                if (ttsResponse.getFilePath() == null) {
                    throw new IOException("Invalid response: missing file_path");
                }
                return ttsResponse.getFilePath();
            }
        }
    }
}
